// pages/store-count/index.js
// const WXAPI = require('../../miniprogram_npm/apifm-wxapi/index')
Page({

  /**
   * 页面的初始数据
   */
  data: {
    loading: false,
    // 今日
    todayNewUsers: 0,
    todayNewOrders: 0,
    todayFreeOrders: 0,
    // 排队免单统计
    queuePending: 0,
    queueCompleted: 0,
    queueRefunded: 0,
    // 累计
    totalUsers: 0,
    totalOrders: 0,
    totalRevenue: '0.00',
    // 更新时间
    lastUpdated: ''
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad() {
    this.loadStats()
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    // 可按需刷新
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  async onPullDownRefresh() {
    try {
      await this.loadStats()
    } finally {
      wx.stopPullDownRefresh()
    }
  },

  /**
   * 加载统计数据（预留真实接口，当前使用模拟数据）
   */
  async loadStats() {
    if (this.data.loading) return
    this.setData({ loading: true })

    try {
      // TODO: 替换为真实接口
      // const token = wx.getStorageSync('token')
      // const res = await WXAPI.xxx({ token })
      // if (res.code === 0) {
      //   this.applyStats(res.data)
      // }

      // 模拟请求耗时
      const mock = await this.getMockStats()
      this.applyStats(mock)
    } catch (e) {
      console.error('加载统计失败', e)
      wx.showToast({ title: '加载失败', icon: 'none' })
    } finally {
      this.setData({ loading: false, lastUpdated: this.formatTime(new Date()) })
    }
  },

  /**
   * 应用统计数据到视图
   */
  applyStats(data) {
    this.setData({
      todayNewUsers: data.todayNewUsers,
      todayNewOrders: data.todayNewOrders,
      todayFreeOrders: data.todayFreeOrders,
      queuePending: data.queuePending,
      queueCompleted: data.queueCompleted,
      queueRefunded: data.queueRefunded,
      totalUsers: data.totalUsers,
      totalOrders: data.totalOrders,
      totalRevenue: this.fmtAmount(data.totalRevenue)
    })
  },

  /**
   * 模拟数据
   */
  getMockStats() {
    return new Promise(resolve => {
      setTimeout(() => {
        resolve({
          todayNewUsers: 12,
          todayNewOrders: 37,
          todayFreeOrders: 5,
          queuePending: 8,
          queueCompleted: 21,
          queueRefunded: 3,
          totalUsers: 4821,
          totalOrders: 15632,
          totalRevenue: 928345.6
        })
      }, 400)
    })
  },

  /**
   * 金额格式化
   */
  fmtAmount(v) {
    const n = Number(v || 0)
    return n.toFixed(2)
  },

  /**
   * 时间格式化
   */
  formatTime(d) {
    const pad = (n) => (n < 10 ? '0' + n : '' + n)
    const y = d.getFullYear()
    const m = pad(d.getMonth() + 1)
    const day = pad(d.getDate())
    const h = pad(d.getHours())
    const mi = pad(d.getMinutes())
    const s = pad(d.getSeconds())
    return `${y}-${m}-${day} ${h}:${mi}:${s}`
  }
})